<template>
  <n-card>
    <!--职位查询-->
    <n-form inline :model="queryParams" label-placement="left">
      <n-form-item label="职位名称" path="name">
        <n-input v-model:value="queryParams.name" :clearable="true" />
      </n-form-item>
      <n-form-item label="职位状态" path="name">
        <n-select
          v-model:value="queryParams.status"
          style="width: 160px"
          :options="stateTypeList"
          :clearable="true"
        />
      </n-form-item>
      <n-form-item>
        <n-button attr-type="button" @click="reloadTable">查询</n-button>
      </n-form-item>
    </n-form>

    <!--页面表格信息-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      v-model:checked-row-keys="checkedRowKeys"
    >
      <template #tableTitle>
        <n-button type="primary" @click="onOpenAddPost">新增职位</n-button>
      </template>
      <template #toolbar>
        <n-button type="error" @click="onDeletePosts">批量删除</n-button>
        <n-button class="ml10" @click="onExport">导出</n-button>
      </template>
    </BasicTable>

    <!--新增或修改职位-->
    <n-modal
      :show-icon="false"
      v-model:show="modelInfo.show"
      preset="dialog"
      :title="modelInfo.info.id ? '修改职位' : '新增职位'"
    >
      <n-form
        :model="modelInfo.info"
        ref="postForm"
        label-placement="left"
        :label-width="80"
        class="py-4"
        :rules="postFormRules"
      >
        <n-form-item label="职位名称" path="positionName">
          <n-input placeholder="请输入职位名称" v-model:value="modelInfo.info.positionName" />
        </n-form-item>
        <n-form-item label="职位状态" path="status">
          <n-radio-group v-model:value="modelInfo.info.status">
            <n-space>
              <n-radio v-for="item in stateTypeList" :key="item.value" :value="item.value">
                {{ item.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="备注" path="date">
          <n-input type="textarea" v-model:value="modelInfo.info.remark" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="modelInfo.show = false">取消</n-button>
          <n-button type="info" @click="onAddOrEditPost">确认</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="tsx" setup>
  import { h, ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { useInitDict } from '@/hooks/dictHooks';
  import { NTag, NButton, useMessage } from 'naive-ui';
  import {
    addPostApi,
    deletePostApi,
    deletePostsApi,
    getPostListApi,
    modifyPostApi,
    exportPostApi,
  } from '@/api/system/post';
  import { debounce, exportFile } from '@/utils';

  import { activeColumnHooks } from '@/hooks/activeColumnHooks';
  import { messageHooks } from '@/hooks/baseHooks';

  const { message, IDialog } = messageHooks();

  const actionRef = ref();
  const postForm = ref();
  const postFormRules = reactive({
    positionName: [{ required: true, message: '职位名称不能为空', trigger: 'blur' }],
  });

  let modelInfo = reactive({
    show: false,
    info: {},
  }); //显示新增修改弹窗

  function resetModelInfo() {
    modelInfo.show = false;
    modelInfo.info = {
      id: undefined,
      positionName: undefined,
      status: 'ENABLE',
      remark: undefined,
    };
  }

  //初始化数据字典
  const { menuTypeDict, viewTypeDict, yesNoDict, requestTypeDict, stateTypeList } = useInitDict({
    MENU_TYPE: 'menuTypeDict',
    VIEW_TYPE: 'viewTypeDict',
    YES_NO: 'yesNoDict',
    REQUEST_TYPE: 'requestTypeDict',
    STATUS_TYPE: 'stateTypeList',
  });

  //定义查询条件
  const queryParams = reactive({
    name: '',
  });

  //查询表格数据
  function reloadTable() {
    actionRef.value.refresh(true);
  }

  //定义表格多选中项
  const checkedRowKeys = ref([]);

  //表格列配置
  const columns = [
    {
      type: 'selection',
      fixed: 'left',
    },
    {
      title: '职位名称',
      key: 'positionName',
      align: 'center',
    },
    {
      title: '职位状态',
      key: 'status',
      render(row) {
        return row.status === 'ENABLE' ? (
          <NTag type="success">启用</NTag>
        ) : (
          <NTag type="error">停用</NTag>
        );
      },
    },
    {
      title: '创建时间',
      key: 'createDate',
      render(row) {
        return <span>{row.createDate}</span>;
      },
    },
    {
      title: '备注',
      key: 'remark',
    },
  ];

  //表格操作列配置
  const { actionColumn } = activeColumnHooks(handleDelete, onOpenEditPost);

  //加载表格数据方法
  const loadDataTable = async (pageation) => {
    let params = {
      pageNum: pageation.current,
      pageSize: pageation.pageSize,

      ...queryParams,
    };

    /*let data = {
      current: 1,
      pages: 1,
      pageSize: 10,
      dataList: [
        {
          id: 10,
          positionName: '24332',
          status: 'ENABLE',
          createDate: '24332',
          remark: '',
        },
      ],
    };
    console.log(data);
    return data;*/
    let res = await getPostListApi(params);
    return res.data;
  };

  //点击修改按钮
  function onOpenEditPost(record: Recordable) {
    resetModelInfo();
    modelInfo.info = { ...record };
    modelInfo.show = true;
  }

  //点击删除按钮
  function handleDelete(record: Recordable) {
    IDialog.error('你确定删除当前职位?', () => {
      deletePostApi(record).then((res) => {
        if (res && res.code === 'A00000') {
          reloadTable();
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      });
    });
  }

  /**
   * 批量删除
   */
  function onDeletePosts() {
    if (checkedRowKeys.value.length === 0) {
      message.warning('请选择职位');
      return;
    }

    IDialog.error('确认批量删除吗？', () => {
      deletePostsApi(checkedRowKeys.value).then((res) => {
        if (res && res.code === 'A00000') {
          message.success(res.msg);
          reloadTable();
        }
      });
    });
  }

  /**
   * 导出
   */
  const onExport = debounce(function () {
    if (checkedRowKeys.value.length === 0) {
      message.warning('请选择职位');
      return;
    }

    exportPostApi(checkedRowKeys.value).then((res) => {
      if (res) {
        exportFile('职位.xls', [res]);
        checkedRowKeys.value = [];
      }
    });
  });

  //打开新增职位页面
  function onOpenAddPost() {
    resetModelInfo();
    modelInfo.show = true;
  }

  const onAddOrEditPost = debounce(function () {
    postForm.value.validate((errors) => {
      if (!errors) {
        if (modelInfo.info.id === undefined) {
          // 新增职位
          addPostApi(modelInfo.info).then((res) => {
            if (res.code === 'A00000') {
              message.success(res.msg);
              modelInfo.show = false;
              reloadTable();
            } else {
              console.log('modify failed');
              message.error(res.msg);
            }
          });
        } else {
          // 修改职位
          modifyPostApi(modelInfo.info).then((res) => {
            if (res.code === 'A00000') {
              message.success(res.msg);
              modelInfo.show = false;
              reloadTable();
            } else {
              message.error(res.msg);
            }
          });
        }
      }
    });
  });
</script>

<style scoped></style>
